﻿#define _CRT_SECURE_NO_WARNINGS 1
//归并排序的实现
//递归方式： 
void _MergeSort(int* a, int begin, int end, int* tmp)
{
	if (begin >= end)
		return;
	//计算中间位置的下标 
	int mid = (begin + end) / 2;

	//1.通过向下递归的方式，划分字数组。 
	_MergeSort(a, begin, mid, tmp);
	_MergeSort(a, mid + 1, end, tmp);

	//2.将划分后的子数组进行合并 
	int begin1 = begin, end1 = mid;
	int begin2 = mid + 1, end2 = end;
	int i = begin;
	while (begin1 <= end1 && begin2 <= end2)
	{
		if (a[begin1] < a[begin2])
		{
			tmp[i++] = a[begin1++];
		}
		else
		{
			tmp[i++] = a[begin2++];
		}
	}
	while (begin1 <= end1)
	{
		tmp[i++] = a[begin1++];
	}
	while (begin2 <= end2)
	{
		 tmp[i++] = a[begin2++];
	}

	//3.将合并后的tmp数组部分内容，拷⻉到原始数组a中 
	memcpy(a + begin, tmp + begin, sizeof(int) * (end - begin + 1));
}
void MergeSort(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
		perror("malloc fail");
		return;
	}
	_MergeSort(a, 0, n - 1, tmp);
	free(tmp);
}
//非递归⽅式： 
void MergeSortNonR(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
		perror("malloc fail");
		return;
	}
	int gap = 1;
	while (gap < n)
	{
		for (size_t i = 0; i < n; i += 2 * gap)
		{
			int begin1 = i, end1 = i + gap - 1;
			int begin2 = i + gap, end2 = i + 2 * gap - 1;
			if (end1 >= n || begin2 >= n)
			{
				//区间1右边界超出范围或者区间2左边界超出范围，当前⼀轮循环结束 
				break;
			}
			if (end2 >= n)
			{
				//区间1范围符合要求，区间2右边界超过范围，修正区别2范围为[begin2,n1]

				end2 = n - 1;
			}
				 //合并有序数组 
				int j = begin1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] < a[begin2])
				{
					tmp[j++] = a[begin1++];
				}
				else
				{
					tmp[j++] = a[begin2++];
				}
			}
			while (begin1 <= end1)
			{
				tmp[j++] = a[begin1++];
			}
			while (begin2 <= end2)
			{
				tmp[j++] = a[begin2++];
			}

			//临时数组中有效区间范围导入原数组有效区间 
			memcpy(a + i, tmp + i, sizeof(int) * (end2 - i + 1));
		}
		gap *= 2;
	}
	free(tmp);
}
